#include "gamepanel.h"
#include "ui_gamepanel.h"
#include <Qpainter>
#include <QRandomGenerator>
#include "GameControl.h"
GamePanel::GamePanel(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::GamePanel)
{
    ui->setupUi(this);

    // 1 背景图
    int num = QRandomGenerator::global()->bounded(10);
    QString path = QString(":/images/background-%1.png").arg(num+1);
    m_bkImage.load(path);
    // 2 窗口标题大小
    this->setWindowTitle("欢乐斗地主");
    this->setFixedSize(1000,650);
    // 3 实例化游戏对象
    GameControlInit();

    //4 玩家得分
    updatePlayerScore();

    // 5 切割图片
    initCardMap();
    // 6 游戏中按钮组初始化
    initButtonsGroup();
    // 7  初始化玩家在窗口中上下文环境
    initPlayerContext();





    initGameScene();

    // 定时器实例化
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &GamePanel::onDispatchCard);

    // 发牌
    startDispatchCard();


}

GamePanel::~GamePanel()
{
    delete ui;
}

void GamePanel::GameControlInit()
{
    // 3 实例化游戏控制对象
    m_gameCtl = new GameControl(this);
    m_gameCtl->playerInit();
    Robot* leftRobot = m_gameCtl->getLeftRobat();
    Robot* RightRobot = m_gameCtl->getRightRobat();
    UserPlayer* user = m_gameCtl->getUserPlayer();
    // 存储顺序 左侧机器人 右侧机器人 当前玩家
    m_playerList << leftRobot << RightRobot << user;
}

void GamePanel::updatePlayerScore()
{
    ui->scorepanel->setScore(m_playerList[0]->getScore(),
                             m_playerList[1]->getScore(),
                             m_playerList[2]->getScore());

}
void GamePanel::initCardMap()
{
    // 1. 加载大图
    QPixmap pixmap(":/images/card.png");
    // 2. 计算每张图片大小
    m_cardSize.setWidth(pixmap.width() / 13);
    m_cardSize.setHeight(pixmap.height() / 5);

    // 3. 背景图
    m_cardBackImg = pixmap.copy(2*m_cardSize.width(), 4*m_cardSize.height(),
                                m_cardSize.width(), m_cardSize.height());
    // 正常花色
    for(int i=0, suit=Card::Suit_Begin+1; suit<Card::Suit_End; ++suit, ++i)
    {
        for(int j=0, pt=Card::Card_Begin+1; pt<Card::Card_SJ; ++pt, ++j)
        {
            Card card((Card::CardPoint)pt, (Card::CardSuit)suit);
            // 裁剪图片
            cropImage(pixmap, j*m_cardSize.width(), i*m_cardSize.height(), card);
        }
    }
    // 大小王
    Card c;
    c.setPoint(Card::Card_SJ);
    c.setSuit(Card::Suit_Begin);
    cropImage(pixmap, 0, 4*m_cardSize.height(), c);

    c.setPoint(Card::Card_BJ);
    cropImage(pixmap, m_cardSize.width(), 4*m_cardSize.height(), c);
}

// void GamePanel::initcarMap()
// {
//     //加载大图
//     QPixmap pixmap(":/images/card.png");
//     //2 计算每一张图片的大小
//     m_cardSize.setHeight(pixmap.height() / 5);
//     m_cardSize.setWidth(pixmap.width() / 13);

//     // 3 背景图
//     m_cardBackImg = pixmap.copy(2 * m_cardSize.width(), 4 * m_cardSize.height(), m_cardSize.width(), m_cardSize.height());
//     // 正常花色
//     for(int i = 0, suit = Card::Suit_Begin +1; suit < Card::Suit_End; ++suit,++i)
//     {
//         for(int j = 0, pt = Card::Card_Begin +1; pt < Card::Card_SJ; ++pt,++j)
//         {
//             Card card((Card::CardPoint)pt, (Card::CardSuit)suit);
//             //裁剪图片
//             cropImage(pixmap, j * m_cardSize.width(), i * m_cardSize.height(), card);
//         }

//     }
//     //大小王
//     Card c;
//     c.setPoint(Card::Card_SJ);
//     c.setSuit(Card::Suit_Begin);
//     cropImage(pixmap, 0, 4 * m_cardSize.height(), c);

//     c.setPoint(Card::Card_BJ);
//     cropImage(pixmap, m_cardSize.width(), 4 * m_cardSize.height(), c);
// }

// void GamePanel::cropImage(QPixmap &pix, int x, int y,  Card& c)
// {
//     QPixmap sub = pix.copy(x,y,m_cardSize.width(),m_cardSize.height());
//     CardPanel* panel = new CardPanel(this);
//     panel->setImage(sub,m_cardBackImg);
//     panel->setCard(c);
//     panel->hide();
//     m_cardMap.insert(c,panel);
// }
void GamePanel::cropImage(QPixmap &pix, int x, int y, Card& c)
{
    QPixmap sub = pix.copy(x, y, m_cardSize.width(), m_cardSize.height());
    CardPanel* panel = new CardPanel(this);
    panel->setImage(sub, m_cardBackImg);
    panel->setCard(c);
    panel->hide();
    m_cardMap.insert(c, panel);
}


void GamePanel::initButtonsGroup()
{
    ui->btnGroup->initButtons();
    ui->btnGroup->selectPanel(ButtonGroup::Start);

    connect(ui->btnGroup, &ButtonGroup::startGame, this, [=](){
        // 界面的初始化
        ui->btnGroup->selectPanel(ButtonGroup::Panel::Empaty);
       // m_gameCtl->clearPlayerScore();
        updatePlayerScore();
        // 修改游戏状态 -> 发牌
       // gameStatusPrecess(GameControl::DispatchCard);
        // 播放背景音乐
        //m_bgm->startBGM(80);
    });
    connect(ui->btnGroup,&ButtonGroup::playhand,[=](){});
    connect(ui->btnGroup,&ButtonGroup::pass,[=](){});
    connect(ui->btnGroup,&ButtonGroup::betPoint,[=](){});

}

void GamePanel::initPlayerContext()
{
    // 1. 放置玩家扑克牌的区域
    const QRect cardsRect[] =
        {
            // x, y, width, height
            QRect(90, 130, 100, height() - 200),                    // 左侧机器人
            QRect(rect().right() - 190, 130, 100, height() - 200),  // 右侧机器人
            QRect(250, rect().bottom() - 120, width() - 500, 100)   // 当前玩家
        };
    const QRect playHandRect[] =
        {
            QRect(260, 150, 100, 100),                              // 左侧机器人
            QRect(rect().right() - 360, 150, 100, 100),             // 右侧机器人
            QRect(150, rect().bottom() - 290, width() - 300, 105)   // 当前玩家
        };
    const QPoint roleImgPos[] =
        {
            QPoint(cardsRect[0].left()-80, cardsRect[0].height() / 2 + 20),     // 左侧机器人
            QPoint(cardsRect[1].right()+10, cardsRect[1].height() / 2 + 20),    // 右侧机器人
            QPoint(cardsRect[2].right()-10, cardsRect[2].top() - 10)            // 当前玩家
        };
    //循环
    int index = m_playerList.indexOf(m_gameCtl->getUserPlayer());
    for(int i=0; i<m_playerList.size(); ++i)
    {
        PlayerContext context;
        context.align = i==index ? Horizontal : Vertical;
        context.isFrontSide = i==index ? true : false;
        context.cardRect = cardsRect[i];
        context.playHandRect = playHandRect[i];
        // 提示信息
        context.info = new QLabel(this);
        context.info->resize(160, 98);
        context.info->hide();
        // 显示到出牌区域的中心位置
        QRect rect = playHandRect[i];
        QPoint pt(rect.left() + (rect.width() - context.info->width()) / 2,
                  rect.top() + (rect.height() - context.info->height()) / 2);
        context.info->move(pt);
        // 玩家的头像
        context.roleImg = new QLabel(this);
        context.roleImg->resize(84, 120);
        context.roleImg->hide();
        context.roleImg->move(roleImgPos[i]);
        m_contextMap.insert(m_playerList.at(i), context);
    }

}

void GamePanel::gameStatusPrecess(GameControl::GameStatus status)
{
    // 记录游戏状态
    m_gameStatus = status;
    // 处理游戏状态
    switch(status)
    {
    case GameControl::DispatchCard:
        startDispatchCard();
        break;
    case GameControl::CallingLord:
    {
        // // 取出底牌数据
        // CardList last3Card = m_gameCtl->getSurplusCards().toCardList();
        // // 给底牌窗口设置图片
        // for(int i=0; i<last3Card.size(); ++i)
        // {
        //     QPixmap front = m_cardMap[last3Card.at(i)]->getImage();
        //     m_last3Card[i]->setImage(front, m_cardBackImg);
        //     m_last3Card[i]->hide();
        // }
        // // 开始叫地主
        // m_gameCtl->startLordCard();
        // break;
    }
    //case GameControl::PlayingHand:
        // // 隐藏发牌区的底牌和移动的牌
        // m_baseCard->hide();
        // m_moveCard->hide();
        // // 显示留给地主的三张底牌
        // for(int i=0; i<m_last3Card.size(); ++i)
        // {
        //     m_last3Card.at(i)->show();
        // }
        // for(int i=0; i<m_playerList.size(); ++i)
        // {
        //     PlayerContext &context = m_contextMap[m_playerList.at(i)];
        //     // 隐藏各个玩家抢地主过程中的提示信息
        //     context.info->hide();
        //     // 显示各个玩家的头像
        //     Player* player = m_playerList.at(i);
        //     QPixmap pixmap = loadRoleImage(player->getSex(), player->getDirection(), player->getRole());
        //     context.roleImg->setPixmap(pixmap);
        //     context.roleImg->show();
        // }
        // break;
    default:
        break;
    }
}

void GamePanel::startDispatchCard()
{
    // 重置每张卡牌的属性
    for(auto it = m_cardMap.begin(); it != m_cardMap.end(); ++it)
    {
        it.value()->setSeclected(false);
        it.value()->setFrontSize(true);
        it.value()->hide();
    }

    // 隐藏三张底牌
    for (int i = 0; i < 3; ++i) {
        m_last3Card[i]->hide();
    }
    // 重置玩家窗口上下文
    int index = m_playerList.indexOf(m_gameCtl->getUserPlayer());
    for(int i = 0; i < m_playerList.size(); ++i)
    {
        m_contextMap[m_playerList[i]].lastCards.clear();
        m_contextMap[m_playerList[i]].info->clear();
        m_contextMap[m_playerList[i]].roleImg->clear();
        m_contextMap[m_playerList[i]].isFrontSide = i == index ? true: false;
    }
    // 显示底牌
    m_baseCard->show();
    // 隐藏 按钮面板
    ui->btnGroup->selectPanel(ButtonGroup::Empaty);
    // 启动定时器
    m_timer->start(10);
    // 播放背景音乐

}

void GamePanel::initGameScene()
{

    //1 发牌区的扑克牌
    m_baseCard = new CardPanel(this);
    m_baseCard->setImage(m_cardBackImg, m_cardBackImg);
    //2 发牌过程中移动扑克牌
    m_moveCard = new CardPanel(this);
    m_moveCard->setImage(m_cardBackImg, m_cardBackImg);
    //3 最后三种底牌(用于窗口显示)
    for(int i = 0; i < 3; ++i)
    {
        CardPanel* panel = new CardPanel(this);
        panel->setImage(m_cardBackImg, m_cardBackImg);
        m_last3Card.push_back(panel);
        // panel->hide();
    }
    //扑克牌位置
    m_baseCardPos = QPoint((width() - m_cardSize.width()) / 2,
                           height() / 2 - 100);
    qDebug() << m_baseCardPos ;
    m_baseCard->move(m_baseCardPos);
    m_moveCard->move(m_baseCardPos);

    int base = (width() -3 * m_cardSize.width() - 2 * 10) / 2;
     qDebug() << base ;
    for (int i = 0; i < 3; ++i) {
        m_last3Card[i]->move(base + (m_cardSize.width() +10) * i, 20);
    }
}

void GamePanel::onDispatchCard()
{
    // 记录扑克牌的位置
    static int curMovePos = 0;
    // 当前玩家
    Player* curPlayer = m_gameCtl->getCurrentPlayer();
    if(curMovePos >= 100)
    {
        // 给玩家发一张牌
        Card card = m_gameCtl->takeOneCard();

        curPlayer->storeDispatchCard(card);
        // Cards cs(card);
        //        disposeCard(curPlayer, cs);
        // 切换玩家
        m_gameCtl->setCurrentPlayer(curPlayer->getNextPlayer());
        curMovePos = 0;
        // 发牌动画
        cardMoveStep(curPlayer, curMovePos);
        // 判断牌是否发完了
        if(m_gameCtl->getSurplusCards().CardCount() == 3)
        {
            // 终止定时器
            m_timer->stop();
            // 切换游戏状态
            gameStatusPrecess(GameControl::CallingLord);
            // 终止发牌音乐的播放
            // m_bgm->stopAssistMusic();
            return;
        }
    }
    // 移动扑克牌
    cardMoveStep(curPlayer, curMovePos);
    curMovePos += 15;
}


void GamePanel::cardMoveStep(Player *player, int curPos)
{
    //得到 每个玩家的扑克牌展示区域
    QRect cardRect = m_contextMap[player].cardRect;
    // 每个玩家的单元步长
    int unit[] = {
        (m_baseCardPos.x() - cardRect.right()) / 100,
        (cardRect.left() - m_baseCardPos.x()) / 100,
        (cardRect.top() - m_baseCardPos.y()) / 100
    };
    //每次窗口移动 对应的坐标的位置
    QPoint pos[] = {
        QPoint(m_baseCardPos.x() - curPos * unit[0], m_baseCardPos.y()),
        QPoint(m_baseCardPos.x() + curPos * unit[1], m_baseCardPos.y()),
        QPoint( m_baseCardPos.x(), m_baseCardPos.y() + curPos * unit[2]),

    };

    // 移动扑克牌窗口
    int index = m_playerList.indexOf(player);
    m_moveCard->move(pos[index]);

    // 临界状态
    if(curPos == 0)
    {
        m_moveCard->show();
    }
    if(curPos == 100)
    {
        m_moveCard->hide();
    }
}





void GamePanel::paintEvent(QPaintEvent *ev)
{
    QPainter p(this);
    p.drawPixmap(rect(),m_bkImage);
}
